import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import dbConfig from '../config/sql-server'
import {errorStatus,successStatus} from '../utils/status'
import jwt from 'jsonwebtoken'
const router = new Router()

router.use(bodyParser())

router.get("/info",async (ctx) => {
  ctx.body = "用户信息接口"
})
router.post('/register',async (ctx) =>{
  let {username,password} = ctx.request.body
  if (username && password) {
    // 搜索用户是否存在，不存在注册，存在提示已存在
    let serchData  = await new Promise((resolve,reject) => {
      let searchSql = `select * from users where username='${username}'`
      dbConfig(searchSql,[username,password], (err,data) => {
        if (err) throw err
        resolve(data)
      })
    })
    // 用户名已注册
    if (serchData.length > 0) {
      if (serchData[0].username == username) {
        successStatus.RESULT.msg = "用户名已注册"
        successStatus.RESULT.code = 400
        ctx.status = 400
        ctx.body = successStatus.RESULT
      }
    } else {
      /*
        jwt.sign()
        参数1：对象，要在token保存的书籍，不要带账号密码的书籍
        参数2: 加密的字符串，类似与一个钥匙，随便填，后续解密token的时候，需要使用它
        参数3: 可选参数,是个对象,比如配置过期时间
        参数4: 可选参数，生成token的回调函数
      */ 
      let mytoken = jwt.sign({myusername: username,mypwd:password},'secret',{expiresIn:60*60*1})
      let data  = await new Promise((resolve,reject) => {
        let sql = "insert into users (username,password,token) values(?,?,?)"
        dbConfig(sql,[username,password], (err,data) => {
          if (err) throw err
          resolve(data)
        })
      })
      successStatus.RESULT.code = 200
      successStatus.RESULT.data = {
        username: data.username
      }
      successStatus.RESULT.msg = "新增成功"
      ctx.body = successStatus.RESULT
    }
  } else {
    ctx.status = 400
    errorStatus.RESULT.msg = "用户名或密码为空"
    ctx.body = errorStatus.RESULT
  }
})
router.post("/login",async (ctx) => {
  let {username,password} = ctx.request.body
  if (username && password) {
    let serchData  = await new Promise((resolve,reject) => {
      let searchSql = `select username,password,token from users where username='${username}' and password='${password}'`
      dbConfig(searchSql,[username,password], (err,data) => {
        if (err) throw err
        resolve(data)
      })
    })
    // 用户名已存在
    if (serchData.length > 0) {
      successStatus.RESULT.msg = "登录成功"
      successStatus.RESULT.code = 200
      successStatus.RESULT.data = serchData[0]
      ctx.body = successStatus.RESULT
    } else {
      successStatus.RESULT.code = 400
      ctx.status = 400
      successStatus.RESULT.msg = "用户名或密码错误"
      ctx.body = successStatus.RESULT
    }
  } else {
    errorStatus.RESULT.msg = "用户名或密码为空"
    ctx.body = errorStatus.RESULT
  }
})

export default router